package com.sdp.wz.handleImpl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.wz.db.wz_now_num.entity.WzNowNum;
import com.sdp.wz.db.wz_now_num.service.IWzNowNumService;
import com.sdp.wz.db.wz_now_num.service.impl.WzNowNumServiceImpl;
import com.sdp.wz.handle.WzInOutPutHandle;
import com.sdp.wz.view.WzNowNumView;

import cn.hutool.core.bean.BeanUtil;

@Component
public class WzNowNumHandleImpl extends WzInOutPutHandle{
	
	@Autowired
	private IWzNowNumService iWzNowNumService;
	
	@Autowired
	private WzNowNumServiceImpl wzNowNumServiceImpl;

	@Override
	public BusinessContext execute(BusinessContext businessContext) {
		return ApplicationContextUtils.getBean(WzNowNumHandleImpl.class).wzNowNum(businessContext);	
	}
	
	@Transactional(rollbackFor=Exception.class)
	public BusinessContext wzNowNum(BusinessContext businessContext) {
		Map<String,BigDecimal> dbMap = new HashMap<>();
		List<WzNowNum> dbList = iWzNowNumService.list();
		for(WzNowNum wz : dbList) {
			dbMap.put(wz.getWzNo(), wz.getAlertNumber()==null?BigDecimal.ZERO:wz.getAlertNumber());
		}

		QueryWrapper<WzNowNum> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("1", 1);
		iWzNowNumService.remove(queryWrapper);
		
		QueryWrapper<WzNowNumView> dbQuery = new QueryWrapper<>();
		List<WzNowNumView> li = wzNowNumServiceImpl.queryAllWzNowNum(dbQuery);
		
		
		List<WzNowNum> list = new ArrayList<WzNowNum>();
		WzNowNum wzNowNum = null;
		for(WzNowNumView wz : li) {
			wzNowNum = new WzNowNum();
			BeanUtil.copyProperties(wz, wzNowNum);
			wzNowNum.setCreateTime(LocalDateTime.now());
			if(dbMap.containsKey(wz.getWzNo())) {
				wzNowNum.setAlertNumber(dbMap.get(wz.getWzNo()));
			}else {
				wzNowNum.setAlertNumber(BigDecimal.ZERO);
			}
			list.add(wzNowNum);
		}
		
		iWzNowNumService.saveBatch(list);
		return businessContext;
	}

}
